/*
 * Copyright 2009 Eat Local Food, LLC
 * Copyright (c) 2007 osCommerce (this file was written after
 * code review of osCommerce).
 *
 * This file is part of gwtCommerce.
 *
 * gwtCommerce is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * gwtCommerce is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with gwtCommerce.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.elf.gwt.admin.client.components;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import com.elf.gwt.admin.client.AdminComponentController;
import com.elf.gwt.common.client.access.RequestParameter;
import com.elf.gwt.common.client.model.AbbreviatedProductModel;
import com.elf.gwt.common.client.model.SpecialMetaModel;
import com.elf.gwt.common.client.model.SpecialModel;
import com.elf.gwt.common.client.utils.CommonUtils;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.Hidden;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.InlineHTML;
import com.google.gwt.user.client.ui.InlineLabel;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.datepicker.client.DateBox;

/**
 *  
 */
public class SpecialsComponent extends EditTableComponent
{	
	protected static final String ToggleStatus = "ToggleStatus";

	protected SpecialMetaModel specialMetaModel;
	protected List<SpecialModel> specialModels;
	protected SpecialModel emptySpecialModel;
	protected SpecialModel selectedSpecialModel;

	/**
	 * Constructor
	 */
	public SpecialsComponent(AdminComponentController controller, String stylePrefix)
	{
		super(controller, stylePrefix);
		emptySpecialModel = new SpecialModel();
		specialModels = new ArrayList<SpecialModel>();
		paginate = true;
		tableType = "specials";
	}

	public void additionalRequestParameters()
	{
		if (action != null && action.equals(ToggleStatus))
		{
			addRequestParameter(new RequestParameter("specialId", selectedSpecialModel.getId()));
		}
		super.additionalRequestParameters();
	}

	protected void buildMetaModel(JSONObject jsonObject) throws Exception
	{
		specialMetaModel = new SpecialMetaModel(jsonObject);
		super.buildMetaModel(jsonObject);
	}

	protected void buildModel(JSONArray jsonArray) throws Exception
	{
		specialModels.clear();
		super.buildModel(jsonArray);
	}

	protected void buildModel(JSONObject jsonObject) throws Exception
	{
		SpecialModel model = new SpecialModel(jsonObject);
		specialModels.add(model);
	}

	public void buildFromModel() throws Exception
	{
		numberOfTableEntries = specialModels.size();
		numberOfTableColumns = 4;
		if (edit) numberOfTableColumns = 5;
		extraRows = 2;
		super.buildFromModel();
	}

	public void displayHeader(Grid grid) {
		grid.setText(0, 0, "Product Name");
		grid.setText(0, 1, "Price");
		grid.setText(0, 2, "Expiration");
		grid.setText(0, 3, "Status");
		if (edit) grid.setText(0, 4, "Mark for Deletion");
	}

	public void displayRow(Grid grid, int row, int entryIndex) {
		displayRow(grid, row, specialModels.get(entryIndex));
	}

	public void displayEmptyRow(Grid grid, int row) {
		displayRow(grid, row, emptySpecialModel);
	}

	public void displayRow(Grid grid, int row, SpecialModel model) {
		Date dateExpires = model.getExpiresDate();
		DateTimeFormat df = CommonUtils.dateFormat;
		if (edit) {

			Hidden idHidden = new Hidden();
			idHidden.setName("specialId");
			idHidden.setValue(String.valueOf(model.getId()));
			elements.put("specialId-" + row, idHidden);

			if (model.getId() > 0)
				grid.setText(row, 0, model.getName());
			else {
				ListBox productsListBox = new ListBox();
				productsListBox.addItem("Select ...", "0");
				Iterator<AbbreviatedProductModel> iterProducts = specialMetaModel.getProducts().iterator();
				while(iterProducts.hasNext())
				{
					AbbreviatedProductModel apmodel = iterProducts.next();
					productsListBox.addItem(apmodel.getName(), String.valueOf(apmodel.getId()));
				}
				grid.setWidget(row, 0, productsListBox);
			}

			TextBox priceTextBox = new TextBox();
			priceTextBox.setWidth("100px");
			priceTextBox.setText(String.valueOf(model.getSpecialPrice()));
			elements.put("specialPrice-" + row, priceTextBox);
			grid.setWidget(row, 1, priceTextBox);

			DateBox expirationDateBox = new DateBox();
			expirationDateBox.setFormat(new DateBox.DefaultFormat(df));
			expirationDateBox.setValue(dateExpires);
			elements.put("specialExpiresDate-" + row, expirationDateBox);
			grid.setWidget(row, 2, expirationDateBox);

			ListBox statusListBox = new ListBox();
			statusListBox.addItem("inactive", "0");
			statusListBox.addItem("active", "1");
			if (model.isStatus()) {
				statusListBox.setSelectedIndex(1);
			}
			else {
				statusListBox.setSelectedIndex(0);
			}
			elements.put("specialStatus", statusListBox);
			grid.setWidget(row, 3, statusListBox);

			if (model.getId() > 0) {
				CheckBox deleteCheckBox = new CheckBox();
				elements.put("specialDelete-" + row, deleteCheckBox);
				grid.setWidget(row, 4, deleteCheckBox);
			}
		}
		else {
			InlineLabel nameLabel = new InlineLabel(model.getName());
			nameLabel.addClickHandler(jumpClickHandler);
			nameLabel.addStyleName("ComponentLink");
			nameLabel.addStyleName("index:"+(row-1));
			grid.setWidget(row, 0, nameLabel);
			
			String strPrice = CommonUtils.productPriceDisplay (AdminComponentController.currenciesAdministrationComponent.getCurrencyModel(), model.getPrice(), model.getPrice(), model.getSpecialPrice());
			grid.setHTML(row, 1, strPrice);
			if (dateExpires != null)
				grid.setText(row, 2, df.format(dateExpires));

			Grid statusGrid = new Grid(1, 3);
			if (model.isStatus())
			{
				statusGrid.setWidget(0, 0, new Image(getImageCommonDirectory() + "icon_status_green.gif"));
				statusGrid.setWidget(0, 1, new InlineHTML("&nbsp;"));
				Image offImage = new Image(getImageCommonDirectory() + "icon_status_red_off.gif");
				offImage.addStyleName("ComponentLink");
				offImage.addStyleName("index:"+(row-1));
				offImage.addClickHandler(statusClickHandler);
				statusGrid.setWidget(0, 2, offImage);
			}
			else
			{
				Image offImage = new Image(getImageCommonDirectory() + "icon_status_green_off.gif");
				offImage.addStyleName("ComponentLink");
				offImage.addStyleName("index:"+(row-1));
				offImage.addClickHandler(statusClickHandler);
				statusGrid.setWidget(0, 0, offImage);
				statusGrid.setWidget(0, 1, new InlineHTML("&nbsp;"));
				statusGrid.setWidget(0, 2, new Image(getImageCommonDirectory() + "icon_status_red.gif"));
			}
			grid.setWidget(row, 3, statusGrid);
		}
	}

	public List<SpecialModel> getSpecialModels() {
		return specialModels;
	}

	protected ClickHandler statusClickHandler = new ClickHandler() {
		public void onClick(ClickEvent event) {
			Widget source = (Widget)event.getSource();
			String stylenames = source.getStyleName();
			int loc = stylenames.indexOf("index:");
			stylenames = stylenames.substring(loc+6);
			loc = stylenames.indexOf(" ");
			if (loc > -1) stylenames = stylenames.substring(0, loc);
			int index = Integer.parseInt(stylenames);
			selectedSpecialModel = specialModels.get(index);
			action = ToggleStatus;
			build(true);
		}
	};

	protected ClickHandler jumpClickHandler = new ClickHandler() {
		public void onClick(ClickEvent event) {
			Widget source = (Widget)event.getSource();
			String stylenames = source.getStyleName();
			int loc = stylenames.indexOf("index:");
			stylenames = stylenames.substring(loc+6);
			loc = stylenames.indexOf(" ");
			if (loc > -1) stylenames = stylenames.substring(0, loc);
			int index = Integer.parseInt(stylenames);
			SpecialModel model = specialModels.get(index);
			String history = "EditProductComponent--1--" + model.getCategoryId() + "--" + model.getProductId();
			onSelection(history);
		}
	};
}
